package com.JUC.cha08.sec03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * CAS缺点：ABA型：解决办法：版本号法
 */
public class ABADemo {

    static AtomicInteger atomicInteger = new AtomicInteger(100);
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();// 版本号
            boolean b;
            System.out.println("初代版本号：" + stamp);

            b = atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("是否更新成功：" + b + "\t" + atomicStampedReference.getReference() + "二次版本号：" + atomicStampedReference.getStamp());

            b = atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("是否更新成功：" + b + "\t" + atomicStampedReference.getReference() + "三次版本号：" + atomicStampedReference.getStamp());

            // 暂停几秒钟线程，确保更新到主内存
            try {
                TimeUnit.MILLISECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }, "C").start();


        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();// 版本号
            boolean b;
            
            // 暂停几秒钟线程
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

            b = atomicStampedReference.compareAndSet(100, 200, stamp, atomicStampedReference.getStamp() + 1);
            System.out.println("是否更新成功：" + b + " " + atomicStampedReference.getReference() + "当前版本号：" + atomicStampedReference.getStamp());

        }, "D").start();


    }

    private static void abaHappen() {
        new Thread(() -> {
            atomicInteger.compareAndSet(100, 101);
            // 暂停几秒钟线程
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicInteger.compareAndSet(101, 100);
        }, "A").start();

        new Thread(() -> {
            // 暂停几秒钟线程
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicInteger.compareAndSet(100, 2022);
        }, "B").start();

        // 暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(atomicInteger.get());
    }
}
